//
//  MKUINavigationBarLayoutConstraint.m
//  MKUI
//
//  Created by 苏尚进 on 2025/4/6.
//  Copyright © 2025 moon. All rights reserved.
//

#import "MKUINavigationBarLayoutConstraint.h"
#import "MKUILayoutConstraintItemAttribute.h"

@interface MKUINavigationBarLayoutConstraint()
@property(nonatomic,strong) MKUIFlowLayoutConstraint *headFlowLayout;
@property(nonatomic,strong) MKUIFlowLayoutConstraint *centerFlowLayout;
@property(nonatomic,strong) MKUIFlowLayoutConstraint *footFlowLayout;
@end

@implementation MKUINavigationBarLayoutConstraint
- (id)init{
    if(self=[super init]){
        _layoutDirection = MKUILayoutConstraintDirectionHorizontal;
        _layoutVerticalAlignment = MKUILayoutConstraintVerticalAlignmentCenter;
        _fixSizeToFitsBounds = YES;
        self.headFlowLayout = [[MKUIFlowLayoutConstraint alloc] init];
        self.centerFlowLayout = [[MKUIFlowLayoutConstraint alloc] init];
        self.footFlowLayout = [[MKUIFlowLayoutConstraint alloc] init];
        [self _updateSubLayouts];
    }
    return self;
}
- (id)copyWithZone:(NSZone *)zone{
    MKUINavigationBarLayoutConstraint *obj = [super copyWithZone:zone];
    obj.layoutDirection = self.layoutDirection;
    obj.layoutVerticalAlignment = self.layoutVerticalAlignment;
    obj.contentInsets = self.contentInsets;
    obj.interitemSpacing = self.interitemSpacing;
    obj.fixSizeToFitsBounds = self.fixSizeToFitsBounds;
    obj.headItems = [self.headItems copy];
    obj.centerItems = [self.centerItems copy];
    obj.footItems = [self.footItems copy];
    return obj;
}
- (void)addHeadItem:(id<MKUILayoutConstraintItemProtocol>)item{
    [self.headFlowLayout addItem:item];
}
- (void)removeHeadItem:(id<MKUILayoutConstraintItemProtocol>)item{
    [self.headFlowLayout removeItem:item];
}
- (void)replaceHeadItem:(id<MKUILayoutConstraintItemProtocol>)oldItem with:(nullable id<MKUILayoutConstraintItemProtocol>)newItem{
    [self.headFlowLayout replaceItem:oldItem with:newItem];
}

- (void)addCenterItem:(id<MKUILayoutConstraintItemProtocol>)item{
    [self.centerFlowLayout addItem:item];
}
- (void)removeCenterItem:(id<MKUILayoutConstraintItemProtocol>)item{
    [self.centerFlowLayout removeItem:item];
}
- (void)replaceCenterItem:(id<MKUILayoutConstraintItemProtocol>)oldItem with:(nullable id<MKUILayoutConstraintItemProtocol>)newItem{
    [self.centerFlowLayout replaceItem:oldItem with:newItem];
}

- (void)addFootItem:(id<MKUILayoutConstraintItemProtocol>)item{
    [self.footFlowLayout addItem:item];
}
- (void)removeFootItem:(id<MKUILayoutConstraintItemProtocol>)item{
    [self.footFlowLayout removeItem:item];
}
- (void)replaceFootItem:(id<MKUILayoutConstraintItemProtocol>)oldItem with:(nullable id<MKUILayoutConstraintItemProtocol>)newItem{
    [self.footFlowLayout replaceItem:oldItem with:newItem];
}

- (MKCGAxis)layoutDirectionAxis{
    MKCGAxis X = self.layoutDirection==MKUILayoutConstraintDirectionHorizontal?MKCGAxisX:MKCGAxisY;
    return X;
}
- (void)setHeadItems:(NSArray<id<MKUILayoutConstraintItemProtocol>> *)headItems{
    self.headFlowLayout.items = headItems;
}
- (NSArray<id<MKUILayoutConstraintItemProtocol>> *)headItems{
    return self.headFlowLayout.items;
}
- (void)setCenterItems:(NSArray<id<MKUILayoutConstraintItemProtocol>> *)centerItems{
    self.centerFlowLayout.items = centerItems;
}
- (NSArray<id<MKUILayoutConstraintItemProtocol>> *)centerItems{
    return self.centerFlowLayout.items;
}
- (void)setFootItems:(NSArray<id<MKUILayoutConstraintItemProtocol>> *)footItems{
    self.footFlowLayout.items = footItems;
}
- (NSArray<id<MKUILayoutConstraintItemProtocol>> *)footItems{
    return self.footFlowLayout.items;
}
- (void)setLayoutDirection:(MKUILayoutConstraintDirection)layoutDirection{
    if(_layoutDirection==layoutDirection)return;
    _layoutDirection = layoutDirection;
    [self _updateSubLayouts];
}
- (void)setLayoutVerticalAlignment:(MKUILayoutConstraintVerticalAlignment)layoutVerticalAlignment{
    if(_layoutVerticalAlignment==layoutVerticalAlignment)return;
    _layoutVerticalAlignment = layoutVerticalAlignment;
    [self _updateSubLayouts];
}
- (void)setLayoutHiddenItem:(BOOL)layoutHiddenItem{
    [super setLayoutHiddenItem:layoutHiddenItem];
    [self _updateSubLayouts];
}
- (void)setInteritemSpacing:(CGFloat)interitemSpacing{
    if(_interitemSpacing==interitemSpacing)return;
    _interitemSpacing = interitemSpacing;
    [self _updateSubLayouts];
}
- (void)_updateSubLayouts{
    self.headFlowLayout.layoutDirection = self.layoutDirection;
    self.centerFlowLayout.layoutDirection = self.layoutDirection;
    self.footFlowLayout.layoutDirection = self.layoutDirection;
    
    self.headFlowLayout.layoutHiddenItem = self.layoutHiddenItem;
    self.centerFlowLayout.layoutHiddenItem = self.layoutHiddenItem;
    self.footFlowLayout.layoutHiddenItem = self.layoutHiddenItem;
    
    if(self.layoutDirection==MKUILayoutConstraintDirectionHorizontal){
        self.headFlowLayout.layoutVerticalAlignment = self.layoutVerticalAlignment;
        self.centerFlowLayout.layoutVerticalAlignment = self.layoutVerticalAlignment;
        self.footFlowLayout.layoutVerticalAlignment = self.layoutVerticalAlignment;
        
        self.headFlowLayout.layoutHorizontalAlignment = MKUILayoutConstraintHorizontalAlignmentLeft;
        self.centerFlowLayout.layoutHorizontalAlignment = MKUILayoutConstraintHorizontalAlignmentCenter;
        self.footFlowLayout.layoutHorizontalAlignment = MKUILayoutConstraintHorizontalAlignmentRight;
    }else{
        MKUILayoutConstraintHorizontalAlignment layoutHorizontalAlignment = MKUILayoutConstraintHorizontalAlignmentCenter;
        switch (self.layoutVerticalAlignment) {
            case MKUILayoutConstraintVerticalAlignmentTop:
                layoutHorizontalAlignment = MKUILayoutConstraintHorizontalAlignmentLeft;
                break;
            case MKUILayoutConstraintVerticalAlignmentCenter:
                layoutHorizontalAlignment = MKUILayoutConstraintHorizontalAlignmentCenter;
            case MKUILayoutConstraintVerticalAlignmentBottom:
                layoutHorizontalAlignment = MKUILayoutConstraintHorizontalAlignmentRight;
            default:
                break;
        }
        
        self.headFlowLayout.layoutHorizontalAlignment = layoutHorizontalAlignment;
        self.centerFlowLayout.layoutHorizontalAlignment = layoutHorizontalAlignment;
        self.footFlowLayout.layoutHorizontalAlignment = layoutHorizontalAlignment;
        
        self.headFlowLayout.layoutVerticalAlignment = MKUILayoutConstraintVerticalAlignmentTop;
        self.centerFlowLayout.layoutVerticalAlignment = MKUILayoutConstraintVerticalAlignmentCenter;
        self.footFlowLayout.layoutVerticalAlignment = MKUILayoutConstraintVerticalAlignmentBottom;
    }
    
    self.headFlowLayout.interitemSpacing = self.interitemSpacing;
    self.centerFlowLayout.interitemSpacing = self.interitemSpacing;
    self.footFlowLayout.interitemSpacing = self.interitemSpacing;
}
- (NSArray<id<MKUILayoutConstraintItemProtocol>> *)items{
    NSMutableArray *items = [[NSMutableArray alloc] init];
    [items addObjectsFromArray:self.headItems];
    [items addObjectsFromArray:self.centerItems];
    [items addObjectsFromArray:self.footItems];
    return items;
}
- (void)layoutItems{
    [self layoutItemsWithResizeItems:NO];
}
- (void)layoutItemsWithResizeItems:(BOOL)resizeItems{
    MKUILayoutConstraintItemAttributeSection *line = [self itemAttributeSectionThatFitsBounds:self.bounds resizeItems:resizeItems];
    for(MKUILayoutConstraintItemAttribute *itemAttr in line.itemAttributs){
        [itemAttr applyAttributeWithResizeItems:resizeItems];
    }
}
- (CGSize)sizeThatFits:(CGSize)size resizeItems:(BOOL)resizeItems{
    if(self.hidden) return CGSizeZero;
    UIEdgeInsets insets = self.contentInsets;
    CGRect bounds = CGRectMake(0, 0, size.width, size.height);
    MKUILayoutConstraintItemAttributeSection *line = [self itemAttributeSectionThatFitsBounds:bounds resizeItems:resizeItems];
    CGFloat space = self.interitemSpacing;
    //计算时，以横向为例
    MKCGAxis X = [self layoutDirectionAxis];
    MKCGAxis Y = MKCGAxisReverse(X);
    
    CGSize fitSize = CGSizeZero;
    CGFloat sumWidth = 0;
    CGFloat maxHeight = 0;
    int count = 0;
    CGFloat w = 0;
    CGFloat h = 0;
    CGRect f = CGRectZero;
    for(id<MKUILayoutConstraintItemAttributeProtocol> attr in line.itemAttributs){
        f = attr.layoutFrame;
        w = MKCGRectGetLength(f, X);
        h = MKCGRectGetLength(f, Y);
        if(w>0){
            count++;
            sumWidth += w;
            maxHeight = MAX(maxHeight,h);
        }
    }
    if(count>0){
        sumWidth += space*(count-1);
        MKCGSizeSetLength(&fitSize, X, sumWidth);
        MKCGSizeSetLength(&fitSize, Y, maxHeight);
    }
    if(MKCGSizeGetLength(fitSize, X)<=0||MKCGSizeGetLength(fitSize, Y)<=0){
        //有一边为0时，返回(0,0)代表不显示
        fitSize = CGSizeZero;
    }else{
        //添加上边距
        if(self.fixSizeToFitsBounds){
            MKCGSizeSetLength(&fitSize, X, MKCGSizeGetLength(size, X));
        }else{
            MKCGSizeAddLength(&fitSize, X, MKUIEdgeInsetsGetEdgeSum(insets, X));
        }
        MKCGSizeAddLength(&fitSize, Y, MKUIEdgeInsetsGetEdgeSum(insets, Y));
    }
    return fitSize;
}
- (nullable MKUILayoutConstraintItemAttributeSection *)itemAttributeSectionThatFitsBounds:(CGRect)containerBounds resizeItems:(BOOL)resizeItems{
    MKUILayoutConstraintItemAttributeSection *line = [[MKUILayoutConstraintItemAttributeSection alloc] init];
    
    UIEdgeInsets insets = self.contentInsets;
    CGRect bounds = UIEdgeInsetsInsetRect(containerBounds, insets);
    CGFloat space = self.interitemSpacing;
    //计算时，以横向为例
    MKCGAxis X = [self layoutDirectionAxis];
    MKCGAxis Y = MKCGAxisReverse(X);
    CGRect f_head = bounds;
    CGRect f_center = bounds;
    CGRect f_foot = bounds;
    //先计算左边
    CGSize s_head = [self.headFlowLayout sizeThatFits:f_head.size resizeItems:resizeItems];
    MKCGSizeSetLength(&s_head, X, MIN(MKCGRectGetLength(f_head, X),MKCGSizeGetLength(s_head, X)));//限制在容器内
    f_head.size = s_head;
    CGFloat f_head_w = MKCGRectGetLength(f_head, X);
    if(f_head_w>0) MKCGRectAddLength(&f_foot, X, -f_head_w-space);
    //再计算右边
    CGSize s_foot = [self.footFlowLayout sizeThatFits:f_foot.size resizeItems:resizeItems];
    MKCGSizeSetLength(&s_foot, X, MIN(MKCGRectGetLength(f_foot, X),MKCGSizeGetLength(s_foot, X)));//限制在容器内
    f_foot.size = s_foot;
    CGFloat f_foot_w = MKCGRectGetLength(f_foot, X);
    if(f_head_w>0 || f_foot_w>0){
        //限制中间居中
        CGFloat f_w_max = MAX(f_head_w,f_foot_w);
        MKCGRectSetLength(&f_head, X, f_w_max);
        MKCGRectSetLength(&f_foot, X, f_w_max);
        
        MKCGRectSetMin(&f_center, X, f_w_max+space);
        MKCGRectSetLength(&f_center, X, MKCGRectGetLength(bounds, X)-(f_w_max+space)*2);
        if(f_head_w<=0){
            f_head_w = f_foot_w;
            MKCGRectSetLength(&f_head, X, f_head_w);
        }else if(f_foot_w<=0){
            f_foot_w = f_head_w;
            MKCGRectAddMin(&f_foot, X, -f_foot_w);
        }
    }
    //最后计算中间
    CGSize s_center = [self.centerFlowLayout sizeThatFits:f_center.size resizeItems:resizeItems];
    MKCGSizeSetLength(&s_center, X, MIN(MKCGRectGetLength(f_center, X),MKCGSizeGetLength(s_center, X)));//限制在容器内
    f_center.size = s_center;
    
    MKCGRectAlignment alignY = MKCGRectAlignmentFromMKUILayoutConstraintVerticalAlignment(self.layoutVerticalAlignment);
    MKCGRectAlignToRect(&f_head, Y, alignY, bounds);
    MKCGRectAlignToRect(&f_center, Y, alignY, bounds);
    MKCGRectAlignToRect(&f_foot, Y, alignY, bounds);
    
    MKCGRectAlignMinToRect(&f_head, X, bounds);
    MKCGRectAlignMidToRect(&f_center, X, bounds);
    MKCGRectAlignMaxToRect(&f_foot, X, bounds);
    
    [line addItemAttribute:[[MKUILayoutConstraintItemAttribute alloc] initWithItem:self.headFlowLayout layoutFrame:f_head]];
    [line addItemAttribute:[[MKUILayoutConstraintItemAttribute alloc] initWithItem:self.centerFlowLayout layoutFrame:f_center]];
    [line addItemAttribute:[[MKUILayoutConstraintItemAttribute alloc] initWithItem:self.footFlowLayout layoutFrame:f_foot]];
    return line;
}
@end
